import re

from rest_framework.response import Response

from users.models import User


# 定义用户登陆后　返回的数据　
# 重写相应的方法，原有方法仅仅返回token
# 保存用户的user_id token username
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username,
    }


# django 原有认证系统仅仅检查用户名和密码进行登陆的验证
# 现在需要修改django.contrib.auth.backends.ModelBackend 的authenticate方法
from django.contrib.auth.backends import ModelBackend


# 具体函数的重写如下，　可以拆分成两个函数
# def authenticate(self, request, username=None, password=None, **kwargs):
#     try:
#         if re.match("^1[3-9]\d{9}$", username):
#             user = User.objects.filter(mobile=username).first()
#         else:
#             user = User.objects.filter(username=username).first()
#
#     except User.DoesNotExist:
#         # Run the default password hasher once to reduce the timing
#         # difference between an existing and a non-existing user (#20760).
#         User().set_password(password)
#     else:
#         if user.check_password(password) and self.user_can_authenticate(user):
#             return user

def get_user_by_count(name):
    try:
        if re.match("^1[3-9]\d{9}$", name):
            user = User.objects.filter(mobile=name).first()
        else:
            user = User.objects.filter(username=name).first()

    except User.DoesNotExist:
        return None
    else:
        return user


class UsenameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
         根据用户提供的信息，返回登陆用户，自定义用户认证
         :param request: 本次请求对象
         :param username: 用户名或者手机号[并不一定是用户名!!!]
         :param password: 登陆密码
         :return:
         """
        user = get_user_by_count(username)
        if user is not None and user.check_password(password):
            return user


from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData
from django.conf import settings
from . import constants


def generate_save_user_token_url(user):
    """生成验证邮箱的链接"""
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    # serializer.dumps(数据), 返回bytes类型
    data = {"user_id": user.id}
    token = serializer.dumps(data)
    # token为ｂｙｔｅ类型，需要解码
    token = token.decode()
    # 拼接url地址
    verify_url = settings.VERIFY_EMAIL_HTML + '?token=' + token

    return verify_url


def check_verify_email_token(token):
    """验证邮箱的链接是不是有效的"""
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
        # data的数据类型为字典
        return data["user_id"]
    except BadData:
        return None
